package com.google.code.virtualhockey.vhx.server.servlet.handler

import com.google.code.virtualhockey.vhx.server.servlet.rest.{RestAuthRole, RestCommandRequest, RestCommandHandler}
import scala.sys.SystemProperties
import com.google.code.virtualhockey.vhx.util.LangUtils
import com.google.code.virtualhockey.vhx.server.service.UserService

/**
 * Returns all currently set Java system properties.
 */
object VhxGetServerEnvironment extends RestCommandHandler {

  /**
   * Returns all system properties in a JSON array in the form:
   * [ { "name": "PropertyName", "value": "PropertyValue" }, ... ]
   *
   * The properties are only returned if the connected user is an administrator.
   */
  protected def handle( cmd: RestCommandRequest ): String = {
    // as authentication is not necessarily enforced check it explicitly
    //
    if ( !UserService.isAuthenticated || !UserService.isAdmin )
      return "[{" + LangUtils.toJsonAttribute( "name", "Sorry!" ) + "," + LangUtils.toJsonAttribute( "value", "You are not an administrator." ) + "}]";

    new SystemProperties().map( ( entry ) => {
      val attrName = LangUtils.toJsonAttribute( "name", entry._1 )
      val attrValue = LangUtils.toJsonAttribute( "value", entry._2 )
      "{" + attrName + ", " + attrValue + "}"
    } ).mkString( "[", ",", "]" )
  } 

  protected val requiredAuthRole: RestAuthRole.Value = RestAuthRole.ANY
}
